using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.Bom.Bom;
using WPF_MVVM_Test.MVVM_View.Bom;
using WPF_MVVM_Test.Services.Bom;

namespace WPF_MVVM_Test.MVVM_ViewModel.Bom
{
    /// <summary>
    /// BOM管理页面的ViewModel
    /// </summary>
    public class BomManagementViewModel : BaseViewModel
    {
        private readonly BomService _bomService;
        private string _productNameFilter = "";
        private string _bomNumberFilter = "";
        private int _currentPageIndex = 1;
        private int _pageSize = 20;
        private int _totalCount = 0;
        private int _totalPage = 0;
        private bool _isLoading = false;
        private string _jumpToPage = "";
        private readonly int[] _pageSizeOptions = { 10, 20, 50, 100 };

        /// <summary>
        /// 构造函数
        /// </summary>
        public BomManagementViewModel()
        {
            _bomService = new BomService();
            BomItems = new ObservableCollection<BomItem>();

            // 初始化命令
            SearchCommand = CreateCommand(ExecuteSearch);
            RefreshCommand = CreateCommand(ExecuteRefresh);
            PreviousPageCommand = CreateCommand(ExecutePreviousPage, CanExecutePreviousPage);
            NextPageCommand = CreateCommand(ExecuteNextPage, CanExecuteNextPage);
            FirstPageCommand = CreateCommand(ExecuteFirstPage, CanExecuteFirstPage);
            LastPageCommand = CreateCommand(ExecuteLastPage, CanExecuteLastPage);
            GoToPageCommand = CreateCommand(ExecuteGoToPage, CanExecuteGoToPage);
            DecomposeBomCommand = CreateCommand<BomItem>(ExecuteDecomposeBom);
            EditBomCommand = CreateCommand<BomItem>(ExecuteEditBom);
            AddBomCommand = CreateCommand(ExecuteAddBom);

            // 订阅静态刷新事件
            RequestRefreshData += OnRequestRefreshData;

            // 初始加载数据
            _ = LoadBomDataAsync();
        }

        /// <summary>
        /// 处理静态刷新事件
        /// </summary>
        private async void OnRequestRefreshData()
        {
            await LoadBomDataAsync();
        }

        #region 属性

        /// <summary>
        /// BOM项目集合
        /// </summary>
        public ObservableCollection<BomItem> BomItems { get; }

        /// <summary>
        /// 产品名称过滤条件
        /// </summary>
        public string ProductNameFilter
        {
            get => _productNameFilter;
            set => SetProperty(ref _productNameFilter, value);
        }

        /// <summary>
        /// BOM编号过滤条件
        /// </summary>
        public string BomNumberFilter
        {
            get => _bomNumberFilter;
            set => SetProperty(ref _bomNumberFilter, value);
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int CurrentPageIndex
        {
            get => _currentPageIndex;
            set
            {
                if (SetProperty(ref _currentPageIndex, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    // 通知所有分页相关的命令状态更新
                    OnPropertyChanged(nameof(CanExecutePreviousPage));
                    OnPropertyChanged(nameof(CanExecuteNextPage));
                    OnPropertyChanged(nameof(CanExecuteFirstPage));
                    OnPropertyChanged(nameof(CanExecuteLastPage));
                    OnPropertyChanged(nameof(CanExecuteGoToPage));
                }
            }
        }

        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize
        {
            get => _pageSize;
            set
            {
                if (SetProperty(ref _pageSize, value))
                {
                    // 当每页大小改变时，重置到第一页并重新加载数据
                    CurrentPageIndex = 1;
                    _ = LoadBomDataAsync();
                }
            }
        }

        /// <summary>
        /// 每页大小选项
        /// </summary>
        public int[] PageSizeOptions => _pageSizeOptions;

        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalCount
        {
            get => _totalCount;
            set
            {
                if (SetProperty(ref _totalCount, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                }
            }
        }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPage
        {
            get => _totalPage;
            set
            {
                if (SetProperty(ref _totalPage, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    // 通知所有分页相关的命令状态更新
                    OnPropertyChanged(nameof(CanExecuteNextPage));
                    OnPropertyChanged(nameof(CanExecuteLastPage));
                    OnPropertyChanged(nameof(CanExecuteGoToPage));
                }
            }
        }

        /// <summary>
        /// 是否正在加载
        /// </summary>
        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                if (SetProperty(ref _isLoading, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    // 通知所有分页相关的命令状态更新
                    OnPropertyChanged(nameof(CanExecutePreviousPage));
                    OnPropertyChanged(nameof(CanExecuteNextPage));
                    OnPropertyChanged(nameof(CanExecuteFirstPage));
                    OnPropertyChanged(nameof(CanExecuteLastPage));
                    OnPropertyChanged(nameof(CanExecuteGoToPage));
                }
            }
        }

        /// <summary>
        /// 分页信息显示
        /// </summary>
        public string PageInfo
        {
            get
            {
                if (IsLoading)
                    return "正在加载数据...";

                if (TotalCount == 0)
                    return "暂无数据";

                return $"第 {CurrentPageIndex} 页，共 {TotalPage} 页，总计 {TotalCount} 条记录";
            }
        }

        /// <summary>
        /// 跳转页码输入
        /// </summary>
        public string JumpToPage
        {
            get => _jumpToPage;
            set => SetProperty(ref _jumpToPage, value);
        }

        #endregion

        #region 命令

        /// <summary>
        /// 搜索命令
        /// </summary>
        public ICommand SearchCommand { get; }

        /// <summary>
        /// 刷新命令
        /// </summary>
        public ICommand RefreshCommand { get; }

        /// <summary>
        /// 上一页命令
        /// </summary>
        public ICommand PreviousPageCommand { get; }

        /// <summary>
        /// 下一页命令
        /// </summary>
        public ICommand NextPageCommand { get; }

        /// <summary>
        /// 首页命令
        /// </summary>
        public ICommand FirstPageCommand { get; }

        /// <summary>
        /// 末页命令
        /// </summary>
        public ICommand LastPageCommand { get; }

        /// <summary>
        /// 跳转到指定页命令
        /// </summary>
        public ICommand GoToPageCommand { get; }

        /// <summary>
        /// 分解BOM命令
        /// </summary>
        public ICommand DecomposeBomCommand { get; }

        /// <summary>
        /// 编辑BOM命令
        /// </summary>
        public ICommand EditBomCommand { get; }

        /// <summary>
        /// 新增BOM命令
        /// </summary>
        public ICommand AddBomCommand { get; }

        /// <summary>
        /// 页面导航事件 - 用于通知主窗口切换页面
        /// </summary>
        public static event Action<string> RequestNavigateToPage;

        /// <summary>
        /// 静态刷新事件 - 用于通知所有BomManagementViewModel实例刷新数据
        /// </summary>
        public static event Action? RequestRefreshData;

        /// <summary>
        /// 静态方法 - 触发刷新数据事件
        /// </summary>
        public static void TriggerRefreshData()
        {
            RequestRefreshData?.Invoke();
        }

        #endregion

        #region 命令执行方法

        /// <summary>
        /// 执行搜索
        /// </summary>
        private async void ExecuteSearch()
        {
            CurrentPageIndex = 1; // 搜索时重置到第一页
            await LoadBomDataAsync();
        }

        /// <summary>
        /// 执行刷新
        /// </summary>
        private async void ExecuteRefresh()
        {
            await LoadBomDataAsync();
        }

        /// <summary>
        /// 执行上一页
        /// </summary>
        private async void ExecutePreviousPage()
        {
            if (CanExecutePreviousPage())
            {
                CurrentPageIndex--;
                await LoadBomDataAsync();
            }
        }

        /// <summary>
        /// 执行下一页
        /// </summary>
        private async void ExecuteNextPage()
        {
            if (CanExecuteNextPage())
            {
                CurrentPageIndex++;
                await LoadBomDataAsync();
            }
        }

        /// <summary>
        /// 判断是否可以执行上一页
        /// </summary>
        private bool CanExecutePreviousPage()
        {
            return CurrentPageIndex > 1 && !IsLoading;
        }

        /// <summary>
        /// 判断是否可以执行下一页
        /// </summary>
        private bool CanExecuteNextPage()
        {
            return CurrentPageIndex < TotalPage && !IsLoading;
        }

        /// <summary>
        /// 执行首页
        /// </summary>
        private async void ExecuteFirstPage()
        {
            if (CanExecuteFirstPage())
            {
                CurrentPageIndex = 1;
                await LoadBomDataAsync();
            }
        }

        /// <summary>
        /// 执行末页
        /// </summary>
        private async void ExecuteLastPage()
        {
            if (CanExecuteLastPage())
            {
                CurrentPageIndex = TotalPage;
                await LoadBomDataAsync();
            }
        }

        /// <summary>
        /// 执行跳转到指定页
        /// </summary>
        private async void ExecuteGoToPage()
        {
            if (CanExecuteGoToPage())
            {
                if (int.TryParse(JumpToPage, out int pageNumber))
                {
                    CurrentPageIndex = pageNumber;
                    await LoadBomDataAsync();
                    JumpToPage = ""; // 清空输入框
                }
            }
        }

        /// <summary>
        /// 判断是否可以执行首页
        /// </summary>
        private bool CanExecuteFirstPage()
        {
            return CurrentPageIndex > 1 && !IsLoading;
        }

        /// <summary>
        /// 判断是否可以执行末页
        /// </summary>
        private bool CanExecuteLastPage()
        {
            return CurrentPageIndex < TotalPage && !IsLoading;
        }

        /// <summary>
        /// 判断是否可以执行跳转到指定页
        /// </summary>
        private bool CanExecuteGoToPage()
        {
            if (IsLoading || string.IsNullOrWhiteSpace(JumpToPage))
                return false;

            if (int.TryParse(JumpToPage, out int pageNumber))
            {
                return pageNumber >= 1 && pageNumber <= TotalPage && pageNumber != CurrentPageIndex;
            }

            return false;
        }

        /// <summary>
        /// 执行分解BOM
        /// </summary>
        private void ExecuteDecomposeBom(BomItem bomItem)
        {
            if (bomItem == null) return;

            // TODO: 实现分解BOM功能
            MessageBox.Show($"分解BOM功能开发中...\nBOM编号: {bomItem.BomNumber}\n产品名称: {bomItem.ProductName}",
                          "功能提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        /// <summary>
        /// 执行编辑BOM
        /// </summary>
        private void ExecuteEditBom(BomItem bomItem)
        {
            if (bomItem == null) return;

            // 创建BOM编辑页面并导航
            var editWindow = new BomEditWindow(bomItem);
            editWindow.ShowDialog();

            // 如果编辑成功，刷新数据
            if (editWindow.DialogResult == true)
            {
                _ = LoadBomDataAsync();
            }
        }

        /// <summary>
        /// 执行新增BOM
        /// </summary>
        private void ExecuteAddBom()
        {
            // 触发页面导航事件，通知主窗口切换到BOM新增页面
            RequestNavigateToPage?.Invoke("BOM新增");
        }


        #endregion

        #region 私有方法

        /// <summary>
        /// 加载BOM数据
        /// </summary>
        private async Task LoadBomDataAsync()
        {
            try
            {
                IsLoading = true;

                var queryParams = new BomQueryParams
                {
                    ProductName = ProductNameFilter,
                    BomNumber = BomNumberFilter,
                    PageIndex = CurrentPageIndex,
                    PageSize = PageSize
                };

                var result = await _bomService.GetBomPagedAsync(queryParams);

                // 更新UI（需要在UI线程中执行）
                Application.Current.Dispatcher.Invoke(() =>
                {
                    BomItems.Clear();
                    foreach (var item in result.Data)
                    {
                        BomItems.Add(item);
                    }

                    TotalCount = result.TotalCount;
                    TotalPage = result.TotalPage;
                });
            }
            catch (Exception ex)
            {
                //MessageBox.Show($"加载BOM数据失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        #endregion

        #region 资源释放

        /// <summary>
        /// 释放资源
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _bomService?.Dispose();
            }
            base.Dispose(disposing);
        }

        #endregion
    }
}